package com.my.socket.nio.v29;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/8/21 16:04
 */
public class Reactor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Reactor.class);
    private Selector selector;

    public Reactor(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                this.selector.select();

                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    Runnable runnable = (Runnable) selectionKey.attachment();
                    LOGGER.info("attachment: {}, selector: {}", runnable, this.selector);
                    runnable.run();
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
            }
        }
    }

}
